<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/8 0008
 * Time: 下午 4:24
 */
namespace app\common\command;

use app\admin\model\Stock;
use app\common\DictConstant;
use app\lib\redis\Redis;
use think\Db;
use think\Exception;

class Order{

    public static function cron(){
        self::closeorder();
    }

    private static function closeorder(){
        $Redis = Redis::getRedisConn();
        $orderdata = $Redis->LRange('order_list_queue',0,-1);
        if($orderdata){
            foreach ($orderdata as $v){
                $v = json_decode($v,true);
                if(!empty($v)){
                   if(time()>=$v['invalid_time']){
                       $order = \app\common\model\Order::where('id',$v['order_id'])->field('id,status,my_collect_id')->find();
                       if($order){
                           if($order['status'] == 1){
                                if(self::updateStock($order)){
                                    $Redis->LRem('order_list_queue',json_encode($v),-1);
                                }
                           }else{
                               $Redis->LRem('order_list_queue',json_encode($v),-1);
                           }
                       }else{
                           $Redis->LRem('order_list_queue',json_encode($v),-1);
                       }
                   }
                }

            }
        }

    }

    private static function updateStock($order){
        Db::startTrans();
        try{
            $Orderitem = db('order_item')->where('order_id',$order['id'])->field('product_id,count')->select();
            foreach ($Orderitem as $v){
                $Stock = Stock::where('product_id',$v['product_id'])->find();
                $Stock->setInc('marketable',$v['count']);
                $Stock->setDec('order_stock',$v['count']);
            }
            $order->status = DictConstant::OrderInvalid;
            $order->save();
            if(!empty($order->my_collect_id)){
               db('member_coupon')->where('id',$order->my_collect_id)->update(['status'=>1]);
            }
            Db::commit();
            return true;
        }catch (Exception $ex){
            Db::rollback();
            return false;
        }


    }
}